/**
 * Created by xiniu on 2017/8/29.
 */

import React, {Component, PropTypes} from 'react';
import {
    Image,
    StyleSheet,
    Text,
    TextInput,
    View,
    ScrollView,
    NativeModules,
    Modal,
    TouchableOpacity,
    Platform,
    Dimensions
} from 'react-native';
import Toast from "react-native-simple-toast";
import AppService from "../service/AppService";
import moment from "moment";
import CheckBox from 'react-native-checkbox';
import ImagePicker from "react-native-image-picker";
import Picker from 'react-native-picker';
import suggestHandle from "./suggestHandle";
import CommentList from './components/CommentList';
import RString from '../language/RString';

const check_Img = require('./img/checked.png')
const uncheck_Img = require('./img/uncheck_Img.png')

export default class Handle extends Component {
    // 初始化
    constructor(props){
        super(props);
        this.state = {
            userId:global.userId,
            userName:global.userName,
            suggestId:this.props.id,
            title:RString('edit_detail'),
            suggest:{},
            suggestTitle:'',
            suggestContent:'',
            pickedType:'',
            typeId:'',
            imageList:[],
            uploadImageList:[],
            checkValue:false,
            isProject:false,
            modalShow:false,
            filePath:null
        };
    };

    componentWillMount() {
        let _this = this;
        AppService.getSuggest({id:_this.props.id,tenantId:global.tenantId}).then(data => {
            if (!!data.errors === true && !!data.errors.length > 0) {
                Toast.show(data.errors[0].message);
            } else {
                _this.setState({
                    suggest:data.suggest,
                    suggestTitle:data.suggest.suggestTitle,
                    suggestContent:data.suggest.suggestContent,
                    pickedType:data.suggest.suggestType,
                    typeId:data.suggest.suggestTypeId,
                    isProject:data.suggest.isProject
                })
                if(_this.state.isProject) {
                    _this.setState({
                        checkValue:true
                    })
                } else {

                }
            }

            let vm = {
                businessType:"DOCK",
                businessId: this.state.suggest.id
            };
            // 获取该提案的图片
            AppService.getUploadImage(vm).then(data =>{
                if (!!data.errors === true && !!data.errors.length > 0) {
                    Toast.show(data.errors[0].message);
                } else {
                    _this.setState({
                        imageList:data.attachmentList,
                        uploadImageList:data.attachmentList
                    });
                }
            });
        });
    };

    // 删除图片
    deleteImg(idx,index){
        let _this = this;
        AppService.deleteUploadImage({attachmentId:idx}).then(response=>{
            if (!!response.errors === true && !!response.errors.length > 0) {
                Toast.show(response.errors[0].message);
            } else {
                _this.state.uploadImageList.splice(index,1);
                _this.setState({
                    imageList:_this.state.uploadImageList
                });
            }
        });
    };

    enlargeImg(url) {
        this.setState({
            modalShow:true,
            filePath:url
        });
    }

    closeModal() {
        this.setState({
            modalShow:false
        });
    }

    // 渲染图片
    renderImage = (v, i) =>{
        return (
            <View style={{ position:'relative' }} key={i}>
                <TouchableOpacity onPress={() => this.deleteImg(v.id,i)} style={styles.deleteImage}>
                    <Image source={require('./img/chahao.png')} style={{ width:10,height:10 }}/>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => this.enlargeImg(v.filePath)}>
                    <Image style={styles.uploadImg} source={{uri: v.filePath}} key={i}/>
                </TouchableOpacity>
            </View>
        )
    };

    filterStatus(status){
        switch (status) {
            case 'TO_ACCEPT':
                return RString('toaccept');
                break;
            case 'TO_DEAL':
                return RString('todeal');
                break;
            case 'TO_CLOSE':
                return RString('toclose');
                break;
            case 'CLOSED':
                return RString('closed');
                break;
            case 'REOPEN':
                return RString('reopen');
                break;
            default:
                return RString('newCreate');
                break;
        }
    };

    goBack = () => {
        const{navigator} = this.props;
        if(navigator){
            navigator.pop();
        }
    };

    doClose = () => {
        NativeModules.system.navTo("BACK");
    };

    selectImage() {
        var that = this;
        const options = {
            title: RString('chooseHeadImg'),
            storageOptions: {
                skipBackup: true,
                path: 'images',
                waitUntilSaved: true,
            },
            cancelButtonTitle: RString('cancel'),
            takePhotoButtonTitle: RString('takePhoto'),
            chooseFromLibraryButtonTitle: RString('chooseAlbum'),
            quality: 1,
            noData: true,
            maxWidth: 700,
            maxHeight: 700,
        };
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
                console.warn('User cancelled image picker');
            }
            else if (response.error) {
                console.warn('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.warn('User tapped custom button: ', response.customButton);
            }
            else {
                let file = {
                    uri: '',
                    name: 'photo',
                    type: 'image/jpeg',
                };
                if(Platform.OS === 'android'){
                    file.uri = response.uri
                }else {
                    file.uri = response.uri.replace('file://', '')
                }

                AppService.uploadImage(file,global.passportId).then(response=>{
                    var rep = response;
                    if(!!rep.url && rep.url.length > 0){
                        AppService.uploadbyfileid({
                            fileId:rep.id,
                            businessId: this.state.suggestId,
                            businessType:"DOCK",
                            businessCategory:"COMMON"
                        }).then(response=> {
                            let vm = {
                                businessType:"DOCK",
                                businessId: that.state.suggestId
                            };
                            // 获取该提案的图片
                            AppService.getUploadImage(vm).then(data =>{
                                if (!!data.errors === true && !!data.errors.length > 0) {
                                    Toast.show(data.errors[0].message);
                                } else {
                                    for(var i = 0;i < data.attachmentList.length;i++) {
                                        if(rep.id === data.attachmentList[i].fileId) {
                                            that.state.uploadImageList.push({filePath:rep.url,id:data.attachmentList[i].id});
                                            that.setState({
                                                imageList:that.state.uploadImageList
                                            });
                                        }
                                    }
                                }
                            });
                        });
                    }
                });
            }
        });
    }


    // 查询提案类型
    /*类型选择*/
    selectType(){
        let pickerData = [];
        let selectedValue = [];
        AppService.findSuggestType({pageSize:0,tenantId:global.tenantId}).then(data => {
            console.log(data);
            for(var i=0;i<data.result.length;i++){
                pickerData.push(data.result[i].suggestTypeName);
            }
            selectedValue.push(data.result[0].suggestTypeName);

            Picker.init({
                pickerData,
                selectedValue,
                pickerConfirmBtnText: RString('confirm'),
                pickerCancelBtnText: RString('cancel'),
                pickerTitleText: RString('chooseType'),
                onPickerConfirm: pickedType => {
                    this.setState({
                        pickedType:pickedType[0],
                    });
                    for(var i=0;i<data.result.length;i++){
                        if(this.state.pickedType == data.result[i].suggestTypeName){
                            this.setState({
                                typeId:data.result[i].id,
                            });
                        }
                    }
                },
            });
            Picker.show();
        });
    };

    // 是否为项目切换
    switchCheck(value){
        if(value) {
            this.setState({
                checkValue:false,
                isProject:false
            });
        } else {
            this.setState({
                checkValue:true,
                isProject:true
            });
        }
    }

    cancelEdit = () => {
        const{navigator} = this.props;
        if(navigator){
            navigator.pop();
        }
    };

    // 非空校验
    checkSuggest = (suggest) =>{
        if(suggest != null){
            if(suggest.suggestTitle == null || suggest.suggestTitle.trim() == ""){
                Toast.show(RString('input_title'));
                return false;
            }else if(suggest.suggestContent == null || suggest.suggestContent.trim() == ""){
                Toast.show(RString('input_detail'));
                return false;
            }else if(suggest.suggestTypeId == 0){
                Toast.show(RString('choose_type'));
                return false;
            }else{
                return true;
            }
        }else{
            Toast.show(RString('input_info'));
            return false;
        }
    };

    saveEdit = () => {
        let vm = {
            id: this.state.suggest.id,
            rowVersion: this.state.suggest.rowVersion,
            tenantId: global.tenantId,
            suggestType: this.state.pickedType,
            suggestTypeId: this.state.typeId,
            suggestTitle:this.state.suggestTitle,
            suggestContent: this.state.suggestContent,
            suggestPersonId: this.state.suggest.suggestPersonId,
            suggestTime: moment(Number(this.state.suggest.suggestTime)).format("YYYY-MM-DD HH:mm:ss"),
            isProject: this.state.isProject
        };
        if (this.checkSuggest(vm)) {
            let _this = this;
            if (vm.suggestTitle && vm.suggestTitle.length > 12) {
                Toast.show(RString('max_title'));
            } else {
                AppService.updateSuggest(vm).then(data => {
                    if (!!data.errors === true && !!data.errors.length > 0) {
                        Toast.show(data.errors[0].message);
                    } else {
                        Toast.show(RString('success_edit'));
                        setTimeout(function () {
                            const {navigator} = _this.props;
                            if (navigator) {
                                navigator.push({
                                    name: "suggestHandle",
                                    component: suggestHandle,
                                    params: {
                                        id: _this.props.id
                                    }
                                })
                            }
                        }, 2000);
                    }
                });
            }
        }
    };

    render() {
        let suggest=this.state.suggest;
        return (
            <View style={{ position:'relative',flex:1 }}>
                <Modal
                    animationType='slide'
                    transparent={true}
                    visible={this.state.modalShow}
                    onShow={() => {}}
                    onRequestClose={() => {}} >
                    <TouchableOpacity activeOpacity={1} style={styles.modalLayout} onPress={()=>{this.closeModal()}}>
                        <Image style={styles.modalView}  source={{uri:this.state.filePath+"?x-oss-process=image/resize,m_lfit,w_640,h_640"}} resizeMode="contain"></Image>
                    </TouchableOpacity>
                </Modal>
                <View style={styles.commonHeader}>
                    <TouchableOpacity onPress={this.goBack.bind(this)} style={styles.back}>
                        <Image source={require('./img/leftArrow.png')} />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={this.doClose.bind(this)} style={styles.toIndex}>
                        <Image source={require('./img/chahao.png')}/>
                    </TouchableOpacity>
                    <View style={{ justifyContent:'center' }}>
                        <Text style={{ color:'#fff',fontSize:16 }}>{this.state.title}</Text>
                    </View>
                </View>
                <ScrollView style={styles.wrap}>
                    <View style={styles.detailWrap}>
                        <View style={styles.detailTop}>
                            <View style={styles.imgWrap}>
                               <Image style={styles.themeImg} source={require('./img/theme.png')}/>
                            </View>
                            <View style={{flex:7}}>
                                <TextInput
                                    style={{fontSize:16}}
                                    underlineColorAndroid='transparent'
                                    placeholderTextColor='#A9A9A9'
                                    defaultValue={suggest.suggestTitle}
                                    onChangeText={(text)=> this.setState({suggestTitle:text})}
                                />
                            </View>
                        </View>
                        <View style={styles.detail}>
                            <View style={styles.imgWrap}>
                                <Image style={styles.themeImg} source={require('./img/record.png')}/>
                            </View>
                            <View style={[styles.wordWrap,{paddingTop:0,paddingBottom:0}]}>
                                <TextInput
                                    style={{flex:1,fontSize:16}}
                                    underlineColorAndroid='transparent'
                                    placeholderTextColor='#A9A9A9'
                                    defaultValue={suggest.suggestContent}
                                    multiline={true}
                                    numberOfLines={2}
                                    textAlignVertical="top"
                                    onChangeText={(text)=> this.setState({suggestContent:text})}
                                />
                            </View>
                        </View>
                        <View style={styles.detail}>
                            <View style={styles.imgWrap}>
                                <Image style={styles.themeImg} source={require('./img/person.png')}/>
                            </View>
                            <View style={styles.wordWrap}>
                                <View style={{flex:5}}>
                                    <Text style={styles.detailFont} numberOfLines={1}>{this.state.userName}{RString('submit')}</Text>
                                </View>
                                <View style={{flex:6,flexDirection:'row',justifyContent:'flex-end'}}>
                                    <Text style={styles.detailTime}>{moment(new Date(Number(suggest.suggestTime))).format('YYYY/MM/DD HH:MM')}</Text>
                                </View>
                            </View>
                        </View>
                        <View style={styles.detail}>
                            <View style={styles.imgWrap}>
                                <Image style={styles.themeImg} source={require('./img/floor.png')}/>
                            </View>
                            <TouchableOpacity style={styles.wordWrap} onPress={this.selectType.bind(this)}>
                                <Text style={{fontSize:16,color:'#000'}} numberOfLines={1}>{this.state.pickedType}</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.detail}>
                            <View style={styles.imgWrap}>
                                <Image style={styles.themeImg} source={require('./img/clock.png')}/>
                            </View>
                            <View style={styles.wordWrap}>
                                <Text style={styles.detailFont}>{this.filterStatus(suggest.status)}</Text>
                            </View>
                        </View>
                        <View style={styles.detail}>
                            <View style={styles.imgWrap}>
                                <Image style={styles.themeImg} source={require('./img/image.png')}/>
                            </View>
                            <View style={[styles.wordWrap,{flexWrap:'wrap',paddingLeft:5,paddingBottom:5}]}>
                                {this.state.imageList.map((v, i) => this.renderImage(v, i))}
                                <TouchableOpacity onPress={()=>{this.selectImage()}}>
                                    <Image style={styles.uploadImg} source={require('./img/addImage.png')}/>
                                </TouchableOpacity>
                            </View>
                        </View>
                        <View style={styles.detail}>
                            <View style={styles.imgWrap}>
                                <Image style={styles.themeImg} source={require('./img/project.png')}/>
                            </View>
                            <View style={styles.lastWordWrap}>
                                <Text style={styles.detailFont}>{this.state.isProject ? RString('isOEProject') : RString('notOEProject')}</Text>
                                <View style={styles.checkWrap}>
                                    <CheckBox label='' checkboxStyle={{justifyContent:'flex-end'}} underlayColor="#fff" checked={this.state.checkValue} uncheckedImage={uncheck_Img} checkedImage={check_Img} onChange={() => this.switchCheck(this.state.checkValue)}/>
                                </View>
                            </View>
                        </View>
                    </View>
                    <View style={{ flex:1 }}>
                        <View style={styles.comment}>
                            <Text style={{ color:'#000' }}>{RString('comment')}</Text>
                        </View>
                        <CommentList suggestId={this.state.suggestId}/>
                    </View>
                    <View style={styles.buttonWrap}>
                        <View style={{ flex:1,flexDirection:'row',justifyContent:'flex-start' }}>
                            <TouchableOpacity style={styles.editBtn} onPress={this.cancelEdit.bind(this)}>
                                <Text style={{ color:'#424242' }}>{RString('cancel')}</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={{ flex:1,flexDirection:'row',justifyContent:'flex-end' }}>
                            <TouchableOpacity style={styles.distributeBtn} onPress={this.saveEdit.bind(this)}>
                                <Text style={{ color:'#fff' }}>{RString('save')}</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </ScrollView>
            </View>
        );
    };
}

const styles = StyleSheet.create({
    modalLayout:{
        width:Dimensions.get('window').width,
        height:Dimensions.get('window').height,
        backgroundColor:'rgba(0,0,0,.8)'
    },
    modalView:{
        width:Dimensions.get('window').width,
        height:Dimensions.get('window').height
    },
    wrap:{
        backgroundColor:'#fff'
    },
    commonHeader:{
        height: Platform.OS === 'android'? 50 : 60,
        paddingTop: Platform.OS === 'ios'? 20 : 0,
        backgroundColor:'#333238',
        flexDirection:'row',
        justifyContent:'center',
        position:'relative'
    },
    back:{
        width:30,
        position:'absolute',
        left:20,
        top:0,
        height: Platform.OS === 'android'? 50 : 60,
        paddingTop: Platform.OS === 'ios'? 20 : 0,
        justifyContent:'center'
    },
    toIndex:{
        width:30,
        position:'absolute',
        left:70,
        top:0,
        height: Platform.OS === 'android'? 50 : 60,
        paddingTop: Platform.OS === 'ios'? 20 : 0,
        justifyContent:'center'
    },
    detailWrap :{
        flex: 1,
        paddingLeft:10,
        paddingRight:10
    },
    detail : {
        paddingLeft:10,
        paddingRight:6,
        flexDirection: 'row'
    },
    detailTop:{
        paddingTop: Platform.OS === 'ios'?15:0,
        paddingBottom:  Platform.OS === 'ios'?15:0,
        paddingLeft:10,
        paddingRight:6,
        borderBottomWidth:1,
        borderStyle:'solid',
        borderBottomColor:'#eee',
        flexDirection: 'row'
    },
    imgWrap:{
        flex:1,
        justifyContent: 'center'
    },
    themeImg:{
        width:16,
        height:16,
        marginLeft:10
    },
    wordWrap:{
        flex:7,
        borderBottomWidth:1,
        borderStyle:'solid',
        borderBottomColor:'#eee',
        paddingTop:15,
        paddingBottom:15,
        flexDirection: 'row'
    },
    lastWordWrap:{
        flex:7,
        paddingTop:15,
        paddingBottom:15,
        flexDirection: 'row'
    },
    detailFont:{
        fontSize:16,
        color:'#000',
        flex:5
    },
    detailFontBold:{
        fontWeight:'bold',
        fontSize:16,
        color:'#000'
    },
    detailTime:{
        fontSize:14,
        color:'#999'
    },
    uploadImg:{
      width:80,
      height:80,
      marginRight:10,
      marginBottom:10
    },
    checkWrap:{
      flex:1,
      flexDirection:'row',
      justifyContent:'flex-end'
    },
    comment:{
        flex:1,
        height:25,
        paddingLeft:20,
        paddingRight:20,
        backgroundColor:'#ECECF1',
        justifyContent: 'center'
    },
    buttonWrap:{
        flex:1,
        height:55,
        backgroundColor:'#F5F5F5',
        paddingLeft:20,
        paddingRight:20,
        paddingTop:10,
        paddingBottom:10,
        flexDirection:'row'
    },
    editBtn:{
        width:100,
        borderWidth:0.5,
        borderStyle:'solid',
        borderColor:'#333',
        borderRadius:5,
        paddingTop:8,
        paddingBottom:8,
        flexDirection:'row',
        justifyContent:'center'
    },
    distributeBtn:{
        width:100,
        borderRadius:5,
        paddingTop:8,
        paddingBottom:8,
        backgroundColor:'#3399FF',
        flexDirection:'row',
        justifyContent:'center'
    },
    deleteImage:{
        width:20,
        height:20,
        position:'absolute',
        top:0,
        right:10,
        zIndex:2,
        backgroundColor:'rgba(0,0,0,.7)',
        paddingLeft:5,
        paddingRight:5,
        justifyContent:'center'
    }
});
